package com.javaweb.bookstore.controller;

import com.javaweb.bookstore.component.IBookManager;
import com.javaweb.bookstore.component.JdbcBookManager;
import com.javaweb.bookstore.entity.Book;
import com.javaweb.bookstore.entity.ResponseEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("book")
public class BookController {
    @Autowired ApplicationContext context;
    @Autowired IBookManager manager;//服务的消费者

    static  final String file_path="book_images";


    @PostMapping ("create")
    public ResponseEntity create(@RequestParam("image") MultipartFile file, Book book) throws IOException {
        String  id = UUID.randomUUID().toString();
        InputStream in = file.getInputStream();
        byte[] buffer = new byte[1024];
        String fname = file.getOriginalFilename();
        String ext = fname.split("\\.")[1];
        File dir = new File(file_path);
        if(!dir.exists()){
            dir.mkdir();
        }

        File localFile = new File(file_path + "/" + id + "." + ext);

        OutputStream out = new FileOutputStream(localFile);



        while(true){
            int l = in.read(buffer);
            if(l <=0)
                break;
            out.write(buffer,0, l);

        }
        out.close();



 //       Book book = new Book();
  //      book.setId(id);book.setName(name);book.setPrice(price);

        //图片存到某目录中，图片文件名等于产品id

        JdbcBookManager bean = context.getBean(JdbcBookManager.class);
        Map<String, IBookManager> bs = context.getBeansOfType(IBookManager.class);

        manager.createBook(book);


        ResponseEntity re = new ResponseEntity(true, "create success!", null);
        return re;
    }
    @GetMapping("search")
    public ResponseEntity search(String keyword){

        List<Book> data = manager.getBooks(keyword);
        ResponseEntity re = new ResponseEntity(true, "remove success!", data);
        return re;
    }

    @PostMapping("upload")
    public ResponseEntity upload(@RequestParam("file") MultipartFile file){
        return new ResponseEntity(true, "", null);

    }



}
